#pragma once
#include <iostream>
#include <algorithm>
#include <string>
#include <sys/types.h>
#include <cstring>
#include <sys/socket.h>
#include <errno.h>
#include <arpa/inet.h>
#include <memory>
#include <netinet/in.h>
#include <unistd.h>
#include <signal.h>
#include <assert.h>
#include <sys/wait.h>
#include <pthread.h>
#include "log.hpp"
class Sock
{
public:
    const static int gbacklog = 20;
    Sock() {}
    int Socket()
    {
        // 1. 创建socket -- 进程和文件
        int listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (listensock < 0)
        {
            logMessage(FATAL, "create socket error, %d:%s", errno, strerror(errno));
            exit(2);
        }
        logMessage(NORMAL, "create socket success, listensock: %d", listensock); // 3
        return listensock;
    }

    void Bind(int sock, uint16_t port, std::string ip = "0.0.0.0")
    {
        int opt_val = 1;
        if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &opt_val, sizeof(opt_val)))
        {
            std::cout << "set reuseport error:  " << errno << std::endl;
            exit(-1);
        }

        // 2. bind -- 文件 + 网络
        struct sockaddr_in local;
        memset(&local, 0, sizeof local); // 初始化
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = ip.empty() ? INADDR_ANY : inet_addr(ip.c_str());
        if (bind(sock, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            logMessage(FATAL, "bind error, %d:%s", errno, strerror(errno));
            exit(3);
        }
    }

    void Listen(int sock)
    {
        // 3. 因为TCP是面向连接的，当我们正式通信的时候，需要先建立连接
        if (listen(sock, gbacklog) < 0)
        {
            logMessage(FATAL, "listen error, %d:%s", errno, strerror(errno));
            exit(4);
        }

        logMessage(NORMAL, "init server success");
    }

    // 一般经验
    // const std::string &: 输入型参数
    // std::string *: 输出型参数
    // std::string &: 输入输出型参数

    int Accept(int listensock, std::string *ip, uint16_t *port)
    {
        struct sockaddr_in src;
        socklen_t len = sizeof(src);

        int serversock = accept(listensock, (sockaddr *)&src, &len); // 有连接就连接，没有就阻塞
        if (serversock < 0)
        {
            logMessage(ERROR, "accept error:%d:%s", errno, strerror(errno));
            return -1;
        }
        if (port)
            *port = ntohs(src.sin_port);
        if (ip)
            *ip = inet_ntoa(src.sin_addr);
        return serversock;
    }

    bool Connect(int sock, const std::string &server_ip, const uint16_t &server_port)
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(server_port);
        server.sin_addr.s_addr = inet_addr(server_ip.c_str());
        if (connect(sock, (struct sockaddr *)(&server), sizeof(server)) == 0)
            return true;
        else
            return false;
    }
    ~Sock()
    {
    }
};
